package com.kgc.sbt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kgc.sbt.beans.*;
import com.kgc.sbt.constant.WxpayConstant;
import com.kgc.sbt.service.OrderService;
import com.kgc.sbt.service.WxpayService;
import com.kgc.sbt.utils.PageSupport;
import com.kgc.sbt.utils.RequestResult;
import com.kgc.sbt.utils.ResultBuildUtil;
import com.kgc.sbt.utils.WxpayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created on 2021/8/17.
 * <p>
 * Author: wuqilong
 * <p>
 * Description: 订单操作入口
 */
@RestController
@Slf4j
@Api(tags = "8 订单操作入口")
@RequestMapping("/wechatPay")
public class OrderController extends BaseController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private WxpayService wxpayService;

    /**
     * 商品总价
     */
    private double totalPrice;

    /**
     * 商品使用优惠券优惠金额
     */
    private double couponsPrice;

    /**
     * 会员优惠金额
     */
    private double vipPrice;

    /**
     * 支付金额
     */
    private double totalPriceByDisCount;

    /**
     * 订单编号
     */
    private String orderNum = "";

    /**
     * @author : 武
     * @date : 2021/8/22
     * @return : com.kgc.sbt.utils.RequestResult<java.util.Map<java.lang.String,java.lang.String>>
     * @description : 展示用户购买的商品，即用户在购物车中勾选并下单的商品
     */
    @RequestMapping(value = "/showOrderProduct", method = RequestMethod.POST)
    @ApiOperation(value = "展示用户购买的商品", notes = "支持统一返回")
    @ApiResponses({
            @ApiResponse(code = 10001, message = "用户标识token为空"),
            @ApiResponse(code = 10002, message = "用户标识token非法"),
            @ApiResponse(code = 10003, message = "购物车中没有商品")
    })
    public RequestResult<Map<String, CartProductReturn>> showOrderProduct(HttpServletRequest request){
        // 获取用户标识的token
        String token = request.getHeader("token");

        if(token == null){
            log.error("------ 用户标识token为空 ------");
            return ResultBuildUtil.fail("10001", "用户标识token为空");
        }

        // 根据token获取用户id
        Integer userId = orderService.selectIdByToken(token);
        // 判断用户id是否合法
        if(userId == 0){
            log.error("------ token非法，无法识别用户 ------");
            return ResultBuildUtil.fail("10002", "用户标识token非法");
        }

        // 用户id合法，查询用户在购物车中勾选的商品
        List<Cart> cartList = orderService.queryCartInfo(userId);

        // 判断购物车是否为空
        if (cartList == null || cartList.size() == 0) {
            log.error("------ 该用户购物车为空，无法下单 ------");
            return ResultBuildUtil.fail("10003", "购物车中没有商品");
        }

        // 展示用户勾选商品的具体信息
        Map<String, CartProductReturn> stringCartProductReturnHashMap = new HashMap<>();
        for (int i = 0; i < cartList.size(); i++) {
            CartProductReturn cartProductReturn = new CartProductReturn();
            Product productTemp = orderService.queryProductById(cartList.get(i).getProductId());
            cartProductReturn.setProductName(productTemp.getProductName());
            cartProductReturn.setProductDescription(productTemp.getProductDescription());
            cartProductReturn.setPrice(productTemp.getPrice());
            cartProductReturn.setQuantity(cartList.get(i).getQuantity());
            stringCartProductReturnHashMap.put(productTemp.getProductCode(), cartProductReturn);
        }
        return ResultBuildUtil.success(stringCartProductReturnHashMap);
    }

    /**
     * @return :
     * @author : 武
     * @date : 2021/8/18
     * @description : 从购物车中下单购买商品
     */
    @RequestMapping(value = "/orderByCart", method = RequestMethod.POST)
    @ApiOperation(value = "从购物车中下单购买商品", notes = "支持统一返回")
    @ApiResponses({
            @ApiResponse(code = 10001, message = "用户标识token为空"),
            @ApiResponse(code = 10002, message = "用户标识token非法"),
            @ApiResponse(code = 10003, message = "购物车中没有商品"),
            @ApiResponse(code = 20004, message = "用户账户内没有优惠券或所有优惠券已过期"),
            @ApiResponse(code = 20005, message = "不支持类型的优惠券"),
            @ApiResponse(code = 20006, message = "用户账户内没有此类型优惠券或此类型优惠券已过期"),
            @ApiResponse(code = 20007, message = "此类型优惠券已过期"),
            @ApiResponse(code = 20008, message = "生成二维码链接失败")
    })
    public RequestResult<Map<String, String>> orderByCart(HttpServletRequest request, @RequestParam(required = false) String couponsNum) throws Exception {

        // 商品总计，即订单金额
        totalPrice = 0.0;

        // 优惠券优惠金额
        couponsPrice = 0.0;

        // 会员优惠金额-九折
        vipPrice = 0.0;

        // 支付金额
        totalPriceByDisCount = 0.0;

        // 获取用户标识的token
        String token = request.getHeader("token");

        if(token == null){
            log.error("------ 用户标识token为空 ------");
            return ResultBuildUtil.fail("10001", "用户标识token为空");
        }

        // 根据token获取用户id
        Integer userId = orderService.selectIdByToken(token);
        // 判断用户id是否合法
        if(userId == 0){
            log.error("------ token非法，无法识别用户 ------");
            return ResultBuildUtil.fail("10002", "用户标识token非法");
        }

        // 用户id合法，从购物车中获取该用户选中的商品
        List<Cart> cartList = orderService.queryCartInfo(userId);

        // 判断购物车是否为空
        if (cartList == null || cartList.size() == 0) {
            log.error("------ 该用户购物车为空，无法下单 ------");
            return ResultBuildUtil.fail("10003", "购物车中没有商品");
        }

        // 判断优惠券类型是否合法
        if(!"YHM1001".equals(couponsNum) && !"YHQ1002".equals(couponsNum) && !"YHD1003".equals(couponsNum)) {
            return ResultBuildUtil.fail("20005", "不支持类型的优惠券");
        }

        // 计算商品总价格
        for (int i = 0; i < cartList.size(); i++) {
            totalPrice += cartList.get(i).getQuantity() * cartList.get(i).getPrice().doubleValue();
        }

        // 用户不使用优惠券
        if(couponsNum == null){
            totalPriceByDisCount = totalPrice;
            couponsPrice = 0;
            // 判断用户是否为会员
            if(orderService.queryVipInfo(userId) == 1) {
                vipPrice = (double) Math.round(totalPriceByDisCount * 0.1 * 100) / 100;
                totalPriceByDisCount = totalPriceByDisCount - vipPrice;
                log.info("------ 用户为钻石会员，会员折扣九折，折扣后的价格为：{} ------", totalPriceByDisCount);
            }

            // 生成订单编号
            orderNum = WxpayUtil.generateOutTradeNo();

            // 进行支付（微信支付）
            String wxpayOrderXml = wxpayService.getWxpayOrderParamsXml("用户购物车下单", 1, this.getRemoteIp(request), orderNum);

            log.info("------ 1 请求微信官方统一下单参数：{} ------", wxpayOrderXml);

            // 请求微信官方进行统一下单
            Map<String, String> wxpayOrderReturnMap = wxpayService.sendToWxpayUnifiedOrder(wxpayOrderXml);

            log.info("------ 2 请求微信官方统一下单返回结果：{} ------", wxpayOrderReturnMap);

            // 自定义返回数据集合
            Map<String, String> wxpayOrderData = new HashMap<>();

            // 结果解析和返回
            if (WxpayConstant.WXPAY_RETURN_CODE_SUCCESS.equals(wxpayOrderReturnMap.get("return_code"))
                    && WxpayConstant.WXPAY_RETURN_CODE_SUCCESS.equals(wxpayOrderReturnMap.get("result_code"))) {

                // 交易类型
                wxpayOrderData.put("trade_type", wxpayOrderReturnMap.get("trade_type"));

                // 预支付交易会话标识
                wxpayOrderData.put("prepay_id", wxpayOrderReturnMap.get("prepay_id"));

                // 二维码链接
                wxpayOrderData.put("code_url", wxpayOrderReturnMap.get("code_url"));

                Integer quantitySum = 0;

                // 查询用户地址信息
                Address address = orderService.queryAddressInfo(userId);

                // 将订单信息插入订单主表中
                OrderMain orderMain = new OrderMain();
                orderMain.setOrderNum(orderNum);
                orderMain.setUserId(userId);
                orderMain.setReceiverName(address.getReceiverName());
                orderMain.setReceiverPhone(address.getReceiverMobile());
                orderMain.setReceiverProvince(address.getReceiverProvince());
                orderMain.setReceiverCity(address.getReceiverCity());
                orderMain.setReceiverDistrict(address.getReceiverDistrict());
                orderMain.setReceiverAddress(address.getReceiverAddress());
                orderMain.setPayType("微信");
                orderMain.setOrderAmount(String.valueOf(totalPrice));
                orderMain.setCouponsAmount(String.valueOf(couponsPrice));
                orderMain.setVipAmount(String.valueOf(vipPrice));
                orderMain.setFreight("包邮");
                orderMain.setPayAmount(String.valueOf(totalPriceByDisCount));
                orderMain.setLogisticsId(1);
                orderMain.setOrderTime(new Date());
                orderMain.setPayTime(new Date());
                orderMain.setOrderStatus(2);
                // 一元钱十积分-不足一的忽略，即向下取整
                orderMain.setOrderIntegral(String.valueOf(Math.floor(totalPriceByDisCount * 10)));

                orderService.insertOrderMain(orderMain);

                // 将订单中的商品信息插入商品详情表中
                // 从购物车中获取该用户选中的商品
                List<Product> productList = new ArrayList<>();

                for (int i = 0; i < cartList.size(); i++) {
                    quantitySum += cartList.get(i).getQuantity();
                    productList.add(orderService.queryProductById(cartList.get(i).getProductId()));

                    // 修改商品占用库存
                    orderService.updateProductStock(cartList.get(i).getProductId(), cartList.get(i).getQuantity());
                }

                for (int j = 0; j < productList.size(); j++) {
                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setOrderNum(orderNum);
                    orderDetail.setProductId(productList.get(j).getProductId());
                    orderDetail.setProductName(productList.get(j).getProductName());
                    orderDetail.setProductQuantity(cartList.get(j).getQuantity());
                    orderDetail.setProductPrice(String.valueOf(productList.get(j).getPrice()));
                    orderDetail.setTotalPrice(String.valueOf(totalPrice));
                    orderDetail.setFavorableAverage(String.valueOf((double) Math.round((totalPrice - totalPriceByDisCount) / quantitySum * 100) / 100));

                    orderService.insertOrderDetail(orderDetail);
                }

                // 变更用户积分
                orderService.updateUserPoints(userId, (int) Math.floor(totalPriceByDisCount * 10));

                // 将已购买的商品从购物车表中删除
                orderService.deleteCartProduct(userId);

                return ResultBuildUtil.success(wxpayOrderData);
            }
        }

        // 用户使用优惠券，判断用户是否拥有未过期优惠券
        List<UserCoupons> userCouponsList = orderService.queryCouponsInfo(userId);

        if (userCouponsList == null || userCouponsList.size() == 0) {
            totalPriceByDisCount = totalPrice;
            log.info("------ 用户账户内没有优惠券或所有优惠券已过期 ------");
            return ResultBuildUtil.fail("20004", "用户账户内没有优惠券或所有优惠券已过期");
        } else {

            // 判断用户是否拥有此类型的且未过期的优惠券
            List<UserCoupons> userCouponsList1 = orderService.queryCoupons(userId, couponsNum);
            if(userCouponsList1 == null){
                return ResultBuildUtil.fail("20006", "用户账户内没有此类型优惠券或此类型优惠券已过期");
            }

            for (int i = 0; i < userCouponsList1.size(); i++) {

                // 判断用户拥有的且未过期的优惠券类型并进行优惠(单个订单优惠不能叠加)
                if ("YHM1001".equals(couponsNum)) {
                    // 用户选择满减优惠券，判断总价是否超过200元，超过优惠20元
                    if (totalPrice > 200) {
                        couponsPrice = 20;
                        totalPriceByDisCount = totalPrice - couponsPrice;
                    }
                    log.info("------ 用户使用满减优惠，优惠前的价格为：{}，优惠后的价格为：{} ------", totalPrice, totalPriceByDisCount);

                    // 将用户使用的优惠券删除
                    orderService.deleteCoupons(userCouponsList1.get(i).getCouponsId());

                    break;
                }

                if ("YHQ1002".equals(couponsNum)) {
                    // 用户选择全品优惠券，判断用户购买总商品超过是否超过6件且总消费超过300元，满足则每个单件优惠8元
                    Integer allQuantity = 0;

                    for (int j = 0; j < cartList.size(); j++) {

                        allQuantity += cartList.get(j).getQuantity();

                        if (allQuantity > 6 && totalPrice > 300) {
                            couponsPrice = allQuantity  * 8.0;
                        }
                    }
                    totalPriceByDisCount = totalPrice - couponsPrice;
                    log.info("------ 用户使用单品优惠，优惠前的价格为：{}，优惠后的价格为：{} ------", totalPrice, totalPriceByDisCount);

                    // 将用户使用的优惠券删除
                    orderService.deleteCoupons(userCouponsList1.get(i).getCouponsId());

                    break;
                }

                if ("YHD1003".equals(couponsNum)) {
                    // 用户选择单品优惠券，判断用户购买商品单价是否低于80元，满足则为一个单件优惠5元
                    for (int k = 0; k < cartList.size(); k++) {
                        if (cartList.get(k).getPrice().doubleValue() > 80) {
                            couponsPrice += 5;
                        }
                    }
                    totalPriceByDisCount = totalPrice - couponsPrice;
                    log.info("------ 用户使用单品优惠，优惠前的价格为：{}，优惠后的价格为：{} ------", totalPrice, totalPriceByDisCount);

                    // 将用户使用的优惠券删除
                    orderService.deleteCoupons(userCouponsList1.get(i).getCouponsId());

                    break;
                }

            }
        }

        // 判断用户是否为会员
        if (orderService.queryVipInfo(userId) == 1) {
            vipPrice = (double) Math.round(totalPriceByDisCount * 0.1 * 100) / 100;
            totalPriceByDisCount = totalPriceByDisCount * 0.9;
            log.info("------ 用户为钻石会员，会员折扣九折，折扣后的价格为：{} ------", totalPriceByDisCount);
        }

        // 生成订单编号
        orderNum = WxpayUtil.generateOutTradeNo();

        // 进行支付（微信支付）
        String wxpayOrderXml = wxpayService.getWxpayOrderParamsXml("用户购物车下单", 1, this.getRemoteIp(request), orderNum);

        log.info("------ 1 请求微信官方统一下单参数：{} ------", wxpayOrderXml);

        // 请求微信官方进行统一下单
        Map<String, String> wxpayOrderReturnMap = wxpayService.sendToWxpayUnifiedOrder(wxpayOrderXml);

        log.info("------ 2 请求微信官方统一下单返回结果：{} ------", wxpayOrderReturnMap);

        // 自定义返回数据集合
        Map<String, String> wxpayOrderData = new HashMap<>();


        // 结果解析和返回
        if (WxpayConstant.WXPAY_RETURN_CODE_SUCCESS.equals(wxpayOrderReturnMap.get("return_code"))
                && WxpayConstant.WXPAY_RETURN_CODE_SUCCESS.equals(wxpayOrderReturnMap.get("result_code"))) {

            // 交易类型
            wxpayOrderData.put("trade_type", wxpayOrderReturnMap.get("trade_type"));

            // 预支付交易会话标识
            wxpayOrderData.put("prepay_id", wxpayOrderReturnMap.get("prepay_id"));

            // 二维码链接
            wxpayOrderData.put("code_url", wxpayOrderReturnMap.get("code_url"));

            Integer quantitySum = 0;

            Address address = orderService.queryAddressInfo(userId);

            // 将订单信息插入订单主表中
            OrderMain orderMain = new OrderMain();
            orderMain.setOrderNum(orderNum);
            orderMain.setUserId(userId);
            orderMain.setReceiverName(address.getReceiverName());
            orderMain.setReceiverPhone(address.getReceiverMobile());
            orderMain.setReceiverProvince(address.getReceiverProvince());
            orderMain.setReceiverCity(address.getReceiverCity());
            orderMain.setReceiverDistrict(address.getReceiverDistrict());
            orderMain.setReceiverAddress(address.getReceiverAddress());
            orderMain.setPayType("微信");
            orderMain.setOrderAmount(String.valueOf(totalPrice));
            orderMain.setCouponsAmount(String.valueOf(couponsPrice));
            orderMain.setVipAmount(String.valueOf(vipPrice));
            orderMain.setFreight("包邮");
            orderMain.setPayAmount(String.valueOf(totalPriceByDisCount));
            orderMain.setLogisticsId(1);
            orderMain.setOrderTime(new Date());
            orderMain.setPayTime(new Date());
            orderMain.setOrderStatus(2);
            // 一元钱十积分-不足一的忽略，即向下取整
            orderMain.setOrderIntegral(String.valueOf(Math.floor(totalPriceByDisCount * 10)));

            orderService.insertOrderMain(orderMain);

            // 将订单中的商品信息插入商品详情表中
            // 从购物车中获取该用户选中的商品
            List<Product> productList = new ArrayList<>();

            for (int i = 0; i < cartList.size(); i++) {
                quantitySum += cartList.get(i).getQuantity();
                productList.add(orderService.queryProductById(cartList.get(i).getProductId()));

                // 修改商品占用库存
                orderService.updateProductStock(cartList.get(i).getProductId(), cartList.get(i).getQuantity());
            }

            for (int j = 0; j < productList.size(); j++) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderNum(orderNum);
                orderDetail.setProductId(productList.get(j).getProductId());
                orderDetail.setProductName(productList.get(j).getProductName());
                orderDetail.setProductQuantity(cartList.get(j).getQuantity());
                orderDetail.setProductPrice(String.valueOf(productList.get(j).getPrice()));
                orderDetail.setTotalPrice(String.valueOf(totalPrice));
                orderDetail.setFavorableAverage(String.valueOf((totalPrice - totalPriceByDisCount) / quantitySum));

                orderService.insertOrderDetail(orderDetail);
            }

            // 变更用户积分
            orderService.updateUserPoints(userId, (int) Math.floor(totalPriceByDisCount * 10));

            // 将已购买的商品从购物车表中删除
            orderService.deleteCartProduct(userId);

            return ResultBuildUtil.success(wxpayOrderData);
        }

        // 返回微信下单接口错误结果
        return ResultBuildUtil.fail("20008", "生成二维码链接失败");
    }

    /**
     * @return :
     * @author : 武
     * @date : 2021/8/17
     * @description : 按照状态（所有，待付款，已支付，待发货，已发货，待收货，已签收）查询用户的订单
     */
    @RequestMapping(value = "/queryOrderByStatus", method = RequestMethod.GET)
    @ApiOperation(value = "根据订单状态查询订单", notes = "支持统一返回，支持分页")
    @ApiResponses({
            @ApiResponse(code = 10001, message = "用户标识token为空"),
            @ApiResponse(code = 10002, message = "用户标识token非法")
    })
    public RequestResult<PageSupport<OrderMain<OrderDetail>>> queryOrderByStatus(HttpServletRequest request, @RequestParam(required = false) Integer orderStatus, @RequestParam Integer currPageNo, @RequestParam Integer pageSize) {

        // 获取用户标识的token
        String token = request.getHeader("token");

        if(token == null){
            log.error("------ 用户标识token为空 ------");
            return ResultBuildUtil.fail("10001", "用户标识token为空");
        }

        // 根据token获取用户id
        Integer userId = orderService.selectIdByToken(token);
        // 判断用户id是否合法
        if(userId == 0){
            log.error("------ token非法，无法识别用户 ------");
            return ResultBuildUtil.fail("10002", "用户标识token非法");
        }

        // 订单状态：1-待付款 2-已支付 3-待发货 4-已发货 5-待收货 6-已签收
        return ResultBuildUtil.success(orderService.queryOrderByStatus(userId, orderStatus, currPageNo, pageSize));
    }

    /**
     * @return :
     * @author : 武
     * @date : 2021/8/17
     * @description : 依据订单编号查询物流信息（只有已发货订单，可以查看物流信息）
     */
    @RequestMapping(value = "/queryLogisticsInfo", method = RequestMethod.GET)
    @ApiOperation(value = "依据订单编号查询物流信息", notes = "支持统一返回")
    @ApiResponses({
            @ApiResponse(code = 30001, message = "订单还未发货")
    })
    public RequestResult<JSONObject> queryLogisticsInfo(@RequestParam String orderNum) {

        // 判断该订单是否处于已发货状态
        OrderMain orderMain = orderService.queryStatusByOrderNum(orderNum);
        if (orderMain.getOrderStatus() < 4) {
            return ResultBuildUtil.fail("30001", "该订单还未发货");
        }

        JSONObject jsonObject = JSON.parseObject(orderService.queryLogisticsInfo("557063438977766"));

        // 查询订单物流信息并返回
        return ResultBuildUtil.success(jsonObject);
    }

    /**
     * @return :
     * @author : 武
     * @date : 2021/8/18
     * @description : 设置到货提醒
     */
    @RequestMapping(value = "/arrivalReminder", method = RequestMethod.GET)
    @ApiOperation(value = "无货-设置到货提醒", notes = "支持统一返回")
    @ApiResponses({
            @ApiResponse(code = 10001, message = "用户标识token为空"),
            @ApiResponse(code = 10002, message = "用户标识token非法"),
            @ApiResponse(code = 40003, message = "用户未设置任何到货提醒"),
            @ApiResponse(code = 40004, message = "已取消到货提醒"),
            @ApiResponse(code = 40005, message = "库存充足，无需设置到货提醒")
    })
    public RequestResult<String> arrivalReminder(HttpServletRequest request, @RequestParam Integer productId, @RequestParam String userPhone) {

        // 获取用户标识的token
        String token = request.getHeader("token");

        if(token == null){
            log.error("------ 用户标识token为空 ------");
            return ResultBuildUtil.fail("10001", "用户标识token为空");
        }

        // 根据token获取用户id
        Integer userId = orderService.selectIdByToken(token);
        // 判断用户id是否合法
        if(userId == 0){
            log.error("------ token非法，无法识别用户 ------");
            return ResultBuildUtil.fail("10002", "用户标识token非法");
        }

        // 判断该用户是否已经设置过该商品的到货提醒，不允许重复设置
        // 遍历到货提醒数据库
        List<ArrivalReminder> arrivalReminderList = orderService.queryAllArrivalReminder();

        if(arrivalReminderList == null){
        } else {
            for (int i = 0; i < arrivalReminderList.size(); i++) {

                if (arrivalReminderList.get(i).getUserId() == userId && arrivalReminderList.get(i).getProductId() == productId) {

                    log.info("------ 该用户已为该商品设置过到货提醒，再次点击取消设置 ------");
                    orderService.deleteArrivalReminder(arrivalReminderList.get(i).getReminderId());

                    return ResultBuildUtil.fail("40004", "已取消到货提醒");
                }
            }
        }

        // 根据商品ID判断库存是否为0，能否设置到货提醒
        Stock stock = orderService.queryStockById(productId);

        if (stock.getCount() == 0 && (orderService.insertArrivalReminder(userId, productId, userPhone))) {

            return ResultBuildUtil.success("设置到货提醒成功，到货时会第一时间发短信提醒您！！！");
        }

        return ResultBuildUtil.fail("40005","该商品库存充足，无需设置到货提醒！！！");
    }

    /**
     * @author : 武
     * @date : 2021/8/23
     * @return : com.kgc.sbt.utils.RequestResult<java.lang.String>
     * @description : 后台查询商品库存，展示无货商品-即用户可以设置到货提醒的商品
     */
    @RequestMapping(value = "/queryProductStock", method = RequestMethod.GET)
    @ApiOperation(value = "查询无库存商品信息", notes = "支持统一返回")
    @ApiResponses({
            @ApiResponse(code = 50001, message = "商品库存充足，无需补货")
    })
    public RequestResult<Map<Integer, CartProductReturn>> queryProductStock() {

        // 遍历商品库存数据库中库存为0的商品信息
        List<Stock> stockList = orderService.queryAllStock();

        if (stockList == null) {
            return ResultBuildUtil.fail("5001", "商品库存充足，无需补货");
        } else {
            Map<Integer, CartProductReturn> cartProductReturnMap = new HashMap<>();
            for (int i = 0; i < stockList.size(); i++) {
                Product product = orderService.queryProductById(stockList.get(i).getProductId());
                CartProductReturn cartProductReturn = new CartProductReturn();
                cartProductReturn.setProductName(product.getProductName());
                cartProductReturn.setProductDescription(product.getProductDescription());
                cartProductReturn.setPrice(product.getPrice());
                cartProductReturn.setQuantity(stockList.get(i).getCount());
                cartProductReturnMap.put(product.getProductId(), cartProductReturn);
            }
            return ResultBuildUtil.success(cartProductReturnMap);
        }
    }

    /**
     * @author : 武
     * @date : 2021/8/23
     * @return : com.kgc.sbt.utils.RequestResult<java.lang.String>
     * @description : 后台商品补货功能，发送到货提醒
     */
    @RequestMapping(value = "/sendArrivalReminder", method = RequestMethod.GET)
    @ApiOperation(value = "商品补货，发送到货提醒", notes = "支持统一返回")
    @ApiResponses({
            @ApiResponse(code = 60001, message = "商品库存数量已达9999，无需补货"),
            @ApiResponse(code = 60002, message = "用户没有为任何商品设置到货提醒")
    })
    public RequestResult<String> sendArrivalReminder(Integer productId, Integer count) {

        // 获取当前商品信息
        Stock stock1 = orderService.queryStockById(productId);
        if(stock1.getCount() > 9999){
            return ResultBuildUtil.fail("6001", "商品库存数量已达9999，无需补货");
        }

        // 增加商品库存
        orderService.updateStock(productId, count);

        // 遍历到货提醒数据库
        List<ArrivalReminder> arrivalReminderList = orderService.queryAllArrivalReminder();

        if (arrivalReminderList == null) {
            log.info("------ 用户没有为任何商品设置到货提醒 ------");
            return ResultBuildUtil.fail("6002", "用户没有为任何商品设置到货提醒");
        } else {
            for (int i = 0; i < arrivalReminderList.size(); i++) {
                Stock stock2 = orderService.queryStockById(arrivalReminderList.get(i).getProductId());

                if (stock2.getCount() > 0) {

                    log.info("------ 向该用户手机：{}发送短信，提醒到货 ------", arrivalReminderList.get(i).getUserPhone());

                    // 发送短信后，将用户设置的到货提醒信息从表中删除，防止一直向用户发送短息
                    orderService.deleteArrivalReminder(arrivalReminderList.get(i).getReminderId());
                }
            }
        }
        return ResultBuildUtil.success("到货提醒已发送");
    }
}

